package com.study.zgw.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

public class WriterServer {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8080));

        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT, null);

        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                if (selectionKey.isAcceptable()) {
                    System.out.println("-----ssc "+ssc);
                    SocketChannel channel = ssc.accept();
                    channel.configureBlocking(false);
                    SelectionKey sk = channel.register(selector, 0, null);
                    sk.interestOps(SelectionKey.OP_READ);

                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i <30000000 ; i++) {
                        sb.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());
                    System.out.println("----总共大小:"+buffer.limit());

                    int write = channel.write(buffer);
                    System.out.println("----发送值大小："+write);

                    if (buffer.hasRemaining()){
                       //关注写事件
                       sk.interestOps(sk.interestOps() + SelectionKey.OP_WRITE);
                       //把未写完的数据挂上
                       sk.attach(buffer);
                    }
                }else if (selectionKey.isWritable()){
                    System.out.println("------->  "+selectionKey.toString());
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = (ByteBuffer) selectionKey.attachment(); //取出挂载的数据
                    int write = channel.write(buffer);
                    System.out.println("----发送值大小："+write);
                    //清理内存buffer
                    if (!buffer.hasRemaining()) {
                        selectionKey.attach(null);
                        selectionKey.interestOps(selectionKey.interestOps() - SelectionKey.OP_WRITE); //本次事件写完 取消关注
                    }
                }
            }
        }
    }

}
